<?php

function sendMessageToAJAX($array)
{
    echo json_encode($array);
}

function getIP()
{
    $ip = $_SERVER[".0
	"] ? $_SERVER["HTTP_CLIENT_IP"] : ($_SERVER["HTTP_X_FORWARDED_FOR"] ? $_SERVER["HTTP_X_FORWARDED_FOR"] : ($_SERVER["REMOTE_ADDR"] ? $_SERVER["REMOTE_ADDR"] : "unknown"));
    $tmp_ary = explode(",", $ip);
    $ip = $tmp_ary[0];
    return $ip;
}

function array_urlencode($data)
{
    $new_data = array();
    if (! empty($data)) {
        foreach ($data as $key => $val) {
            $new_data[urlencode($key)] = is_array($val) ? array_urlencode($val) : urlencode($val);
        }
    }
    return $new_data;
}

function array_urldecode($data)
{
    $new_data = array();
    foreach ($data as $key => $val) {
        $new_data[urldecode($key)] = is_array($val) ? array_urldecode($val) : urldecode($val);
    }
    return $new_data;
}

function conn()
{
    $db = mysql_connect("localhost", "root", "10jqka");
    mysql_query("set names 'utf8'", $db);
    // 判断连接
    if (! $db) {
        die("Database connection failed: " . mysqli_connect_error());
    }
    // 连接数据库
    $db_selected = mysql_select_db("wap3g_dl", $db);
    if (! $db_selected) {
        die("Can't use test : " . mysql_error());
    }
    return $db;
}

function curl_get($url, $for)
{
    global $timeout;
    global $for_nowencai;
    $final = array();
    $final['errorcode'] = "0";
    $final["data"] = array();
    foreach ($for_nowencai as $key_for => $value_for) {
        if ($for == $key_for) {
            $final["data"]['answer_status'] = 0;
            $final["data"]['isResult'] = 0;
            $final["data"]['similar_list'] = null;
            $final["data"]['question_type'] = "";
            $final["data"]['answer'] = $value_for['answer'];
            $final["data"]['saveanswer'] = $value_for['answer'];
            $final["data"]['similar_topic'] = "";
            return $final;
        }
    }
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $ret = curl_exec($ch);
    curl_close($ch);
    if ($ret == false) {
        $final = array();
        $final['errorcode'] = "-1";
        echo json_encode($final);
        exit();
    }
    $results = json_decode($ret, true);
    /* 不同类型做不同的处理 */
    $questionType = $results["response"]['question_type'];
    switch ($questionType) {
        case '问财':
            $results["response"]['answer'] = json_decode($results["response"]['answer'], true);
            $count = count($results["response"]['answer']);
            $str = "";
            for ($i = 0; $i < $count; $i ++) {
                $final["data"]['answer']["stock" . $i]['code'] = $results["response"]['answer'][$i][0];
                $final["data"]['answer']["stock" . $i]['name'] = $results["response"]['answer'][$i][1];
                $final["data"]['answer']["stock" . $i]['info'] = $results["response"]['answer'][$i][2];
                $tmpcount = count($results["response"]['answer'][$i][2]);
                $str .= $final["data"]['answer']["stock" . $i]['name'] . " " . $final["data"]['answer']["stock" . $i]['code'] . " " . '可以从' . $tmpcount . '个角度为您解析，您想看哪方面?<br>' . '<li>';
                foreach ($results["response"]['answer'][$i][2] as $k => $v) {
                    $str .= "<question><lr>" . $k . "分析</lr></question>";
                }
                $str . "</li>";
            }
            $answer = $str;
            break;
        case '搜索类';
            /* 搜索类需要添加topicId字段 ，从similar_question中获取 */
            $similarIds = array();
            $similarQuestion = $results['response']['similar_question'];
            foreach ($similarQuestion as $k => $v) {
                $similarIds[] = $v['topic_id'];
            }
            $final['data']['topicIds'] = $similarIds;
            break;
        case '选股':
            break;
        default:
            break;
    }
    if ('问财' != $questionType) {
        $final["data"]['answer'] = $results["response"]['answer'];
        $answer = $final["data"]['answer'];
    }
    $final["data"]['answer_status'] = $results["response"]['answer_status'];
    $final["data"]['isResult'] = $results["response"]['is_result'];
    $final["data"]['similar_list'] = $results["response"]['simalar_list'];
    $final["data"]['question_type'] = $results["response"]['question_type'];
    $final["data"]['saveanswer'] = $answer;
    $final["data"]['similar_topic'] = $results["response"]['similar_topic'];
    return $final;
}

function getResult($final)
{
    if (empty($final)) {
        return "0";
    }
    if ($final["data"]['question_type'] == "问财" || $final["data"]['question_type'] == "寒暄") {
        return "3";
    }
    if ($final["data"]['isResult'] == 1) {
        return "3";
    }
    return "0";
}

function pic_get($showPlatForm,$appver,$userid){
    if ($_FILES['file']['name']) {
        
        // 检查文件大小
        if (MAR_FILE_SIZE < $_FILES['file']['size']) {
            $final['errorcode'] = - 1;
            $final['errormsg'] = '图片大小不能超过4M';
            sendMessageToAJAX($final);
			exit;
        }
        // 检查文件后缀
        $temp_arr = explode(".", $_FILES['file']['name']);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        if (! in_array($file_ext, json_decode(IMAGE_TYPE))) {
            $final['errorcode'] = - 1;
            $final['errormsg'] = '不支持该格式的图片';
            sendMessageToAJAX($final);
			exit;
        }
        // 另存为新文件
        $target_path = DOCUMENT_DIR . "suggestion_image/";
        $new_filename = $target_path . date('YmdHis') . '_' . $showPlatForm . '_' . $appver . '_' . $userid . time(); // 图片重命名
        $new_filename .= '.jpg';
        // echo copy($_FILES["file"]["tmp_name"],$new_filename);exit;
        if (! copy($_FILES["file"]["tmp_name"], $new_filename)) {
            $final['errorcode'] = - 1;
            $final['errormsg'] = '图片上传失败';
            sendMessageToAJAX($final);
			exit;
        }
        $imagepath = $new_filename;
	}else if(!empty($_REQUEST['file'])){
            $arr = explode(',', substr($_REQUEST['file'], 5), 2);
            
            $data = base64_decode($arr[1]);
            if (MAR_FILE_SIZE < strlen($data)) {
                $final['errorcode'] = - 1;
                $final['errormsg'] = '图片大小不能超过4M';
                sendMessageToAJAX($final);
			exit;
            }
            
            $mime_split_without_base64 = explode(';', $arr[0], 2);
            $mime_split = explode('/', $mime_split_without_base64[0], 2);
            if (count($mime_split) == 2) {
                $extension = $mime_split[1];
                if (! in_array($extension, json_decode(IMAGE_TYPE))) {
                    // 根据mime来判断图片格式
                    $final['errorcode'] = - 1;
                    $final['errormsg'] = '不支持该格式的图片';
                    sendMessageToAJAX($final);
				exit;
                }
                // 另存为新文件
                $target_path = DOCUMENT_DIR . "suggestion_image/";
                $new_filename = $target_path . date('YmdHis') . '_' . $showPlatForm . '_' . $appver . '_' . $userid . time(); // 图片重命名
                $new_filename .= '.jpg';
                if (! file_put_contents($new_filename, $data)) {
                    $final['errorcode'] = - 1;
                    $final['errormsg'] = '图片上传失败';
                    sendMessageToAJAX($final);
				exit;
                }
                $imagepath = $new_filename;
            } else {
                $final['errorcode'] = - 1;
                $final['errormsg'] = '无法识别该类型的文件';
                sendMessageToAJAX($final);
			exit;
            }
        }
    return $imagepath;
}

/* 判断是否是相同问题 */
function isSameQues($username, $question, $answer)
{
    $db = conn();
    $time = date('Y-m-d H:i:s', time() - SAME_QUES_TIME);
    $sql = "select count(*) as count from suggest where user ='$username' and ctime>'$time' and (question='$question' or answer='$answer')";
    $res = mysql_query($sql, $db);
    $result = mysql_fetch_array($res);
    if ($result[0] > 1) {
        return true;
    } else {
        return false;
    }
}

/* 判断是否是工作时间 */
function isWorkTime()
{
    $week = date('w', time());
    if ($week == 0 || $week == 6) {
        return false;
    }
    $startTime = strtotime(date('Y-m-d')) + (3600 * PUSH_START_TIME);
    $endTime = strtotime(date('Y-m-d')) + (3600 * PUSH_END_TIME);
    $nowTime = time();
    if ($nowTime >= $startTime && $nowTime <= $endTime) {
        return true;
    } else {
        return false;
    }
}

/* 在线客服数据库连接操作 */
function connRecord()
{
    $mysqli = new mysqli(RECORD_HOST, RECORD_USER, RECORD_PSW, RECORD_DB);
    if (! $mysqli) {
        return false;
    }
    $mysqli->set_charset("utf8");
    return $mysqli;
}

/* 保存机器人的对话内容 */
function saveRecord($res, $content, $userid, $username, $category, $platform, $userAndSessionCode = '')
{
    global $logContent;
    $robotAndB2BSTime = microtime(true);
    $robotSTime = microtime(true);
    $robotName = '同花顺智能机器人';
    $mysqli = connRecord();
    if (! $mysqli) {
        return false;
    }
    $sql = "insert into robot_chat_record(comment,sender,receiver,category,from_type,bind_answer,sender_name,receiver_name,question_type,ctime,platform,additional_info)" . "values(?,?,?,?,?,?,?,?,?,?,?,?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('ssssissssiss', $content, $sender, $receiver, $category, $from_type, $answer, $senderName, $receiverName, $isSolve, $time, $platform, $additionalInfo);
    /* 存用户问题部分 */
    $category = empty($category) ? 10 : $category; // 空代表的是其他问题---10
    $time = time();
    $comment = $content;
    $sender = $userid;
    $from_type = 2;
    $receiver = 'xxxxxxxxx';
    $senderName = $username;
    $receiverName = $receiver;
    $questionType = $res['data']['question_type'];
    $additionalInfo = '';
    $isSolve = $questionType;
    $answer = $res['data']['answer'];
    switch ($questionType) {
        case '问财':
            $answer = str_replace('您想看哪方面?', '请点击查看：', $res['data']['saveanswer']);
            break;
        case '选股':
            break;
        default:
            break;
    }
    $stmt->execute();
    $paramOfUser = array(
        'companyCode' => 'ths',
        'user_id' => 'socket_' . $userAndSessionCode,
        'question' => $content,
        'sender_name' => $username,
        'robot_name' => $robotName,
        'infoType' => 'user',
        'topic_id' => ''
    );
    /* 存机器人回答部分 */
    $content = $answer;
    $temp = $sender;
    $sender = $receiver;
    $receiver = $temp;
    $answer = 0;
    $from_type = 0;
    $temp = $senderName;
    $senderName = $receiverName;
    $receiverName = $temp;
    $isSolve = "answer_$questionType";
    $stmt->execute();
    $content = isset($res['rawData']) ? $res['rawData'] : '';
    $paramOfRobot = array(
        'companyCode' => 'ths',
        'user_id' => 'socket_' . $userAndSessionCode,
        'question' => $content,
        'sender_name' => $username,
        'robot_name' => $robotName,
        'infoType' => 'robot',
        'topic_id' => ''
    );
    $mysqli->close();
    
    $robotETime = microtime(true);
    $robotExcuteTime = $robotETime - $robotSTime;
    $logContent .= "robotExcuteTime:$robotExcuteTime\n";
    
    /* 同步至B2B在线后台 */
    if ($userAndSessionCode) {
        $b2bSTime = microtime(true);
        synchronousRobotChatToB2b($paramOfUser, $paramOfRobot);
        $b2bETime = microtime(true);
        $b2bExcuteTime = $b2bETime - $b2bSTime;
        $logContent .= "b2bExcuteTime:$b2bExcuteTime\n";
    }
    /* 更新日志 */
    $robotAndB2BETime = microtime(true);
    $robotAndB2BExcuteTime = $robotAndB2BETime - $robotAndB2BSTime;
    $logContent .= "robotAndB2BTotalExcuteTime:$robotAndB2BExcuteTime\n";
}

/* curl封装函数 */
function curl($url, $postfields = '', $headers = '', $timeout = 3, $file = 0)
{
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => false,
        CURLOPT_NOBODY => false,
        CURLOPT_POST => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    );
    if (is_array($postfields) && $file == 0) {
        $options[CURLOPT_POSTFIELDS] = http_build_query($postfields);
    } else {
        $options[CURLOPT_POSTFIELDS] = $postfields;
    }
    curl_setopt_array($ch, $options);
    if (is_array($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    $result = curl_exec($ch);
    $code = curl_errno($ch);
    $msg = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    $data = array(
        'httpCode' => $info['http_code'],
        'htmlContent' => $result,
        'errorCode' => $code,
        'errorMsg' => $msg,
        'info' => $info
    );
    return $data;
}

/* 获取地区信息 */
function getArea()
{
    $ip = getIP();
    $url = sprintf(GET_AREA_INFO, $ip);
    $res = curl($url);
    if (200 != $res['httpCode']) {
        return '';
    }
    $content = json_decode($res['htmlContent'], true);
    $code = $content['code'];
    $city = $content['city'];
    $conditon = array(
        0,
        2,
        4
    );
    if (! in_array($code, $conditon)) {
        return '';
    }
    return $city;
}

/* 获取选股信息 */
function getStockInfo($question)
{
    $res = array();
    $url = sprintf(STOCK_SELECTION, $question);
    $result = curl($url);
    if (200 != $result['httpCode']) {
        return $result;
    }
    $content = json_decode($result['htmlContent'], true);
    $data = $content['xuangu']['blocks'][0]['data'];
    /* 构造返回数据 */
    $title = $data['title'];
    $titleNumber = count($title);
    $info = $data['result'];
    $row = array();
    $i = 1;
    foreach ($info as $k => $v) {
        /* 只取前五条 */
        if ($i > 5) {
            break;
        } else {
            $i ++;
        }
        
        $tmp['code'] = $v[0];
        $tmp['name'] = $v[1];
        $riseAndFull = $v[2];
        if ('' != $riseAndFull) {
            $tmp['riseAndFull'] = $riseAndFull . '%';
        } else {
            $tmp['riseAndFull'] = '--';
        }
        $tmp['presentPrice'] = $v[3];
        /* 对市盈率进行处理 */
        if (4 != $titleNumber) {
            $peRatio = $v[4];
            if ($peRatio >= 10000 && $peRatio < 100000000) {
                $peRatio /= 10000;
                $peRatio = round($peRatio, 2);
                $peRatio .= '万';
            } elseif ($peRatio >= 100000000) {
                $peRatio /= 100000000;
                $peRatio = round($peRatio, 2);
                $peRatio .= '亿';
            }
            $tmp['peRatio'] = $peRatio;
        }
        $row[] = $tmp;
    }
    $jumpUrl = sprintf(STOCK_JUMP_URL, $question);
    
    if (4 == $titleNumber) {
        $res['tableType'] = 2;
    } else {
        $res['tableType'] = 1;
    }
    $res['rowInfo'] = $row; // 股票信息
    $res['jumpUrl'] = $jumpUrl; // 跳转地址
    return $res;
}

/* 添加日志函数 */
function writeLog($msg, $type, $fileName)
{
    $time = date('Y-m-d H:i:s');
    switch ($type) {
        case 0:
            $content = "ERROR   - $time --> $msg \n";
            break;
        case 1:
            $content = "SUCCESS - $time --> $msg \n";
            break;
        case 2:
            $content = "INFO    - $time --> $msg \n";
            break;
        default:
            break;
    }
    file_put_contents($fileName, $content, FILE_APPEND);
}

/* 对接B2B在线客服初始化信息获取 */
function getB2BInfo($userid, $platform)
{
    /* 初始化 */
    $terminal = 0;
    switch ($terminal) {
        case 'iphone':
            $terminal = 1;
            break;
        case 'ghone':
            $terminal = 2;
            break;
        default:
            $terminal = 0;
            break;
    }
    $logPath = B2B_LOG_PATH;
    /* 生成用户编号 */
    $userCodCreateUrl = B2B_USER_CODE_CREATE;
    $postData = array(
        'user_id' => $userid,
        'companyCode' => 'ths'
    );
    $param = json_encode($postData);
    $res = curl($userCodCreateUrl, $postData);
    if (200 != $res['httpCode']) {
        $msg = "msg:生成用户编号失败 -- url:{$userCodCreateUrl} -- httpcode:{$res['httpCode']} -- errorMsg:{$res['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $content = json_decode($res['htmlContent'], true);
    if (1 != $content['code']) {
        $msg = "msg :生成用户编号失败 -- param:{$param} -- res:{$res['htmlContent']}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $userCode = $content['data']; // 用户编号
    /* 生成会话编号 */
    $sessionCodeCreateUrl = B2B_SESSION_CODE_CREATE;
    $postData = array(
        'callbackparam' => 'addChatRecordSuccess',
        'companyCode' => 'ths',
        'customer_id' => 0,
        'type' => 0,
        'app_name' => '',
        'page_name' => '',
        'terminal' => $terminal,
        'user_id' => $userCode
    );
    $param = json_encode($postData);
    $res = curl($sessionCodeCreateUrl, $postData);
    if (200 != $res['httpCode']) {
        $msg = "msg:生成会话编号失败 -- url:{$sessionCodeCreateUrl} -- httpcode:{$res['httpCode']} -- errorMsg:{$res['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $content = json_decode($res['htmlContent'], true);
    if (1 != $content['code']) {
        $msg = "msg:生成会话编号失败 -- url:{$sessionCodeCreateUrl} -- param:{$param} -- res:{$res['htmlContent']}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $sessionCode = $content['data']['record_key']; // 会话编号
    /* 获取初始化信息 */
    $initInfoUrl = B2B_INIT_INFO;
    $postData = array(
        'companyCode' => 'ths'
    );
    $param = json_encode($postData);
    $res = curl($initInfoUrl, $postData);
    if (200 != $res['httpCode']) {
        $msg = "msg:获取初始化信息失败 -- url:{$initInfoUrl} -- httpcode:{$res['httpCode']} -- errorMsg:{$res['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $content = json_decode($res['htmlContent'], true);
    if (1 != $content['code']) {
        $msg = "msg:获取初始化信息失败 -- url:{$initInfoUrl} -- param:{$param} -- res:{$res['htmlContent']}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $customerOvertime = $content['data']['customer_overtime']; // 客服超时时间
    $userLeavetime = $content['data']['user_leavetime']; // 用户超时下线时间
    $userOvertime = $content['data']['user_overtime']; // 用户超时提醒时间
    $customerWelcomeInfo = $content['data']['customer_welcome_info']; // 客服欢迎语
    $customerOverInfo = $content['data']['customer_overinfo']; // 客服超时语
    $userLeaveInfo = $content['data']['user_leaveinfo']; // 用户下线语
    $userOverInfo = $content['data']['user_overinfo']; // 用户超时提醒语
    
    $data = array(
        'userCode' => $userCode,
        'sessionCode' => $sessionCode,
        'customerOvertime' => $customerOvertime,
        'userLeavetime' => $userLeavetime,
        'userOvertime' => $userOvertime,
        'customerWelcomeInfo' => $customerWelcomeInfo,
        'customerOverInfo' => $customerOverInfo,
        'userLeaveInfo' => $userLeaveInfo,
        'userOverInfo' => $userOverInfo
    );
    return $data;
}

/* 新接口转换成老接口兼容 */
function getOldResult($results)
{
    $logFile = TOTAL_CONTROL_LOG_PATH;
    $source = $results['source'];
    $content = $results[txt][0]['content'];
    $content = json_decode($content, true);
    switch ($source) {
        case 'kefu':
            $questionType = $content['question_type'];
            $answer = $content['answer'];
            /* 问题类型为‘标准问答对’的时候需要替换 */
            if ('标准问答对' == $questionType) {
                $questionType = $content['matched_topic_name'];
            }
            break;
        case 'soniu':
            $content = $content['item'];
            $questionType = '主搜索';
            $answer = $content['summ'];
            /* 去掉特殊字符 */
            $specialChar = array(
                urldecode('%EE%81%BE'),
                urldecode('%EE%81%BF')
            );
            $replaceChat = array(
                ' ',
                ' '
            );
            $answer = str_replace($specialChar, $replaceChat, $answer);
            /* answer为空的话，给默认值 */
            if (empty($answer)) {
                $answer = DEFAULT_ANSWER;
            }
            break;
        default:
            $final = array();
            $final['errorcode'] = "-1";
            $param = json_encode($results);
            $msg = "msg:主搜格式无法识别  -- res:{$param}";
            writeLog($msg, 0, $logFile);
            echo json_encode($final);
            exit();
    }
    $newresult = array(
        'response_head' => array(
            'response_head' => 0,
            'msg' => 'ok'
        ),
        'response' => array(
            'similar_topic' => $content['similar_topic'],
            'user_id' => $content['user_id'],
            'similar_question' => $content['similar_question'],
            'question' => $content['question'],
            'answer_status' => $content['answer_status'],
            'is_result' => $content['is_result'],
            'question_type' => $questionType,
            'answer' => $answer,
            'user_name' => '',
            'similar_list' => $content['similar_list']
        )
    );
    return $newresult;
}

/* 评价人工客服的情况 */
function evaluationCustomer()
{
    $evaluation = trim($_REQUEST['result']);
    $customerId = trim($_REQUEST['customerId']);
    $userCode = trim($_REQUEST['userCode']);
    $sessionCode = trim($_REQUEST['sessionCode']);
    if (1 == $evaluation) {
        $evaluation = 0;
    }
    /* 过滤非法参数 */
    $flag = filterEvaluateParam($evaluation, $customerId, $userCode, $sessionCode);
    if (! $flag) {
        return false;
    }
    $logPath = B2B_LOG_PATH;
    $url = B2B_CUSTOMER_EVALUATION;
    $postData = array(
        'type' => 2,
        'user_eva' => $evaluation,
        'customer_id' => $customerId,
        'user_id' => $userCode,
        'chat_code' => $sessionCode,
        'companyCode' => 'ths'
    );
    $param = json_encode($postData);
    $res = curl($url, $postData);
    if (200 != $res['httpCode']) {
        $msg = "msg:会话评价失败 -- url:{$url} -- httpcode:{$res['httpCode']} -- errorMsg:{$res['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
        return false;
    } else {
        $content = json_decode($res['htmlContent'], true);
        if (1 != $content['code']) {
            $msg = "msg:会话评价失败 -- url:{$url} -- param:{$param} -- res:{$res['htmlContent']}";
            writeLog($msg, 0, $logPath);
            return false;
        }
    }
    return true;
}

/* 评价机器人的情况 */
function evaluationRobot()
{
    $db = conn();
    $result = is_numeric($_REQUEST["result"]) ? $_REQUEST["result"] : 0;
    $id = is_numeric($_REQUEST['id']) ? $_REQUEST["id"] : 0;
    if ($result == "" || $id == "") {
        $final['errorcode'] = - 1;
    } else {
        $sql = "update suggest set result=$result where id=$id ";
        mysql_query($sql);
        $str = $id . "_1_" . $result . "\n";
        if (! file_put_contents(UPDATE_RESULT, $str, FILE_APPEND)) {
            cronLog("error_log", $str . "=>submit");
        } else {
            cronLog("data_log", $str . "=>submit");
        }
        $final['errorcode'] = 0;
    }
    sendMessageToAJAX($final);
}

/* 获取问财接口新方法 */
function new_curl_get($url, $for)
{
    /* 初始化 */
    global $for_nowencai;
    global $logContent;
    $totoalControlSTime = microtime(true);
    $final = array();
    $final['errorcode'] = "0";
    $final["data"] = array();
    $logFile = TOTAL_CONTROL_LOG_PATH;
    /* 猎金的平台不接入 */
    foreach ($for_nowencai as $key_for => $value_for) {
        if ($for == $key_for) {
            $final["data"]['answer_status'] = 0;
            $final["data"]['isResult'] = 0;
            $final["data"]['similar_list'] = null;
            $final["data"]['question_type'] = "";
            $final["data"]['answer'] = $value_for['answer'];
            $final["data"]['saveanswer'] = $value_for['answer'];
            $final["data"]['similar_topic'] = "";
            return $final;
        }
    }
    
    /* 向总控请求数据 */
    $getTotalControl = curl($url);
    if (200 != $getTotalControl['httpCode']) {
        $msg = "msg:请求总控失败 -- url:{$url} -- httpcode:{$getTotalControl['httpCode']} -- errorMsg:{$getTotalControl['errorMsg']}";
        writeLog($msg, 0, $logFile);
        $final = array();
        $final['errorcode'] = "-1";
        echo json_encode($final);
        exit();
    }
    $newresults = json_decode($getTotalControl['htmlContent'], true);
    if ('ok' == $newresults['msg'] || 'success' == $newresults['msg']) {
        $newresults['errorcode'] = 0;
        $newAnswer = $newresults['answer'][0]; // 新接口答案
        /* 将主控的数据格式转换成旧的格式，兼容后续操作 */
        $oldresult = getOldResult($newAnswer);
    } else {
        $final = array();
        $final['errorcode'] = "-1";
        echo json_encode($final);
        $msg = "msg:请求总控失败 -- url:{$url} -- res:{$getTotalControl['htmlContent']}";
        writeLog($msg, 0, $logFile);
        exit();
    }
    
    $results = $oldresult;
    /* 不同类型做不同的处理 */
    $questionType = $results["response"]['question_type'];
    switch ($questionType) {
        case '问财':
            $results["response"]['answer'] = json_decode($results["response"]['answer'], true);
            $count = count($results["response"]['answer']);
            $str = "";
            for ($i = 0; $i < $count; $i ++) {
                $final["data"]['answer']["stock" . $i]['code'] = $results["response"]['answer'][$i][0];
                $final["data"]['answer']["stock" . $i]['name'] = $results["response"]['answer'][$i][1];
                $final["data"]['answer']["stock" . $i]['info'] = $results["response"]['answer'][$i][2];
                $tmpcount = count($results["response"]['answer'][$i][2]);
                $str .= $final["data"]['answer']["stock" . $i]['name'] . " " . $final["data"]['answer']["stock" . $i]['code'] . " " . '可以从' . $tmpcount . '个角度为您解析，您想看哪方面?<br>' . '<li>';
                foreach ($results["response"]['answer'][$i][2] as $k => $v) {
                    $str .= "<question><lr>" . $k . "分析</lr></question>";
                }
                $str . "</li>";
            }
            $answer = $str;
            break;
        case '搜索类';
        /* 搜索类需要添加topicId字段 ，从similar_question中获取 */
        $similarIds = array();
            $similarQuestion = $results['response']['similar_question'];
            foreach ($similarQuestion as $k => $v) {
                $similarIds[] = $v['topic_id'];
            }
            $final['data']['topicIds'] = $similarIds;
            break;
        case '选股':
            /* 选股需要添加选股信息 */
            $res = getStockInfo($results['response']['question']);
            $final["data"]['stockInfo'] = $res;
            break;
        default:
            break;
    }
    if ('问财' != $questionType) {
        $final["data"]['answer'] = $results["response"]['answer'];
        $answer = $final["data"]['answer'];
    }
    /* 这部分数据格式是老的数据格式 */
    $final["data"]['answer_status'] = $results["response"]['answer_status'];
    $final["data"]['isResult'] = $results["response"]['is_result'];
    $final["data"]['similar_list'] = $results["response"]['simalar_list'];
    $final["data"]['question_type'] = $results["response"]['question_type'];
    $final["data"]['saveanswer'] = $answer;
    $final["data"]['similar_topic'] = $results["response"]['similar_topic'];
    /* 这部分数据是为了兼容总控和B2B新添加的数据 */
    $final["rawData"] = json_encode($oldresult); // 原始数据
    $final["newData"] = $newresults; // 最后返回给前端的新数据
    /* 更新日志 */
    $totoalControlETime = microtime(true);
    $totoalControlExcuteTime = $totoalControlETime - $totoalControlSTime;
    $logContent .= "totoalControlExcuteTime:$totoalControlExcuteTime\n";
    return $final;
}

/* 判断是否接入人工 */
function accessartificial($answerStatu, $uname, $content, $answer, $for, $questionType)
{
    global $noAccessWebChat;
    /* 不在工作时间不接入 */
    $workTimeFlag = isWorkTime();
    if (! $workTimeFlag) {
        return false;
    }
    
    /* 主搜索不接入 */
    if ('主搜索' == $questionType) {
        return false;
    }
    
    /* 猎金不接入 */
    $appJudge = in_array($for, $noAccessWebChat);
    if ($appJudge) {
        return false;
    }
    
    /* 回答成功并且规定时间没有重复提问 */
    $sameFlag = isSameQues($uname, $content, $answer);
    if (! $sameFlag && 0 != $answerStatu) {
        return false;
    }
    
    return true;
}

/* 将机器人会话部分同步到B2B在线客服后台 */
function synchronousRobotChatToB2b($user, $robot)
{
    $logPath = B2B_LOG_PATH;
    $url = B2B_ROBOT_RECORD_SAVE;
    /* 存用户会话 */
    $param = json_encode($user);
    $result = curl($url, $user);
    if (200 != $result['httpCode']) {
        $msg = "msg:更新机器人会话至B2B失败(用户部分) -- url:{$url} -- httpcode:{$result['httpCode']} -- errorMsg:{$result['errorMsg']} -- parsm:{$param}";
        writeLog($msg, 0, $logPath);
    } else {
        $htmlContent = json_decode($result['htmlContent'], true);
        if (1 != $htmlContent['code']) {
            $msg = "msg:更新机器人会话至B2B失败(用户部分) -- url:{$url} -- param:{$param} -- res:{$result['htmlContent']}";
            writeLog($msg, 0, $logPath);
        }
    }
    
    /* 存机器人会话 */
    if (empty($robot['question'])) {
        return false;
    }
    $param = json_encode($robot);
    $result = curl($url, $robot);
    if (200 != $result['httpCode']) {
        $msg = "msg:更新机器人会话至B2B失败(机器人部分) -- url:{$url} -- httpcode:{$result['httpCode']} -- errorMsg:{$result['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
    } else {
        $htmlContent = json_decode($result['htmlContent'], true);
        if (1 != $htmlContent['code']) {
            $msg = "msg:更新机器人会话至B2B失败(机器人部分) -- url:{$url} -- param:{$param} -- res:{$result['htmlContent']}";
            writeLog($msg, 0, $logPath);
        }
    }
}

/* 过滤评价的非法参数 */
function filterEvaluateParam($evaluation, $customerId, $userCode, $sessionCode)
{
    /* 0为满意，2为不满意 */
    if (0 != $evaluation && 2 != $evaluation) {
        return false;
    }
    
    /* 为空的直接过滤 */
    if (empty($customerId) || empty($userCode) || empty($sessionCode)) {
        return false;
    }
    
    if (- 1 == $customerId || - 1 == $userCode || - 1 == $sessionCode) {
        return false;
    }
    return true;
}

/* 拷贝图片至静态资源服务器 */
function uploadToStatic($file)
{
    $username = "hexiao";
    $password = "hexiao";
    
    $cmd = "curl -d \"user_name=$username&password=$password\" -sig \"http://admin.thsi.cn/index.php?controller=login&action=in\"";
    exec($cmd, $result);
    $ret = implode("!@#%^&", $result);
    $pattern = "/PHPSESSID=[A-Za-z0-9]+/";
    preg_match($pattern, $ret, $pregArray);
    $cookie = $pregArray[0];
    $uploadcmd = "curl -F path=/html/s/css/m/macd/images_ad -F file=@$file -H Cookie:$cookie -sg \"http://admin.thsi.cn/index.php?controller=file&action=upload\"";
    exec($uploadcmd, $uploadresult);
    
    if ($uploadresult[0] == "{success:true}") {
        return 1;
    } else {
        return 0;
    }
}

/* 获取总控请求地址 */
function getTotalUrl($param)
{
    /* 参数初始化 */
    $appToSource = $GLOBALS['appToSource'];
    $for = empty($param['for']) ? 'null' : $param['for'];
    $source = $appToSource[$for];
    $username = urlencode($param['username']);
    $question = urlencode($param['question']);
    $logid = time() . rand(1000, 9999);
    $additionInfo = array(
        'kefu' => array(
            'source' => $param['source']
        )
    );
    $additionInfo = urlencode(json_encode($additionInfo));
    $url = sprintf(NEW_URL, $source, $param['userid'], $username, $logid, $question, $additionInfo);
    return $url;
}

/* 拷贝图片到另外一台服务器 */
function copyImage($imgPath)
{
    $logPath = PIC_COPY_LOG_PATH;
    $url = IMAGE_COPY_INTERFACE;
    $picture = class_exists(CURLFile) ? new CURLFile(realpath($imgPath)) : "@{$imgPath}";
    $data = array(
        'pic' => $picture,
        'type' => 'curl'
    );
    $param = json_encode($data);
    $resultOfCurl = curl($url, $data, '', '', 1);
    if (200 != $resultOfCurl['httpCode']) {
        $msg = "msg:请求图片上传接口失败 -- httpcode:{$resultOfCurl['httpCode']} -- errorMsg:{$resultOfCurl['errorMsg']} -- param:{$param}";
        writeLog($msg, 0, $logPath);
        return false;
    }
    $htmlContent = json_decode($resultOfCurl['htmlContent'], true);
    if (1 == $htmlContent['code']) {
        return $htmlContent['url'];
    } else {
        $msg = "msg:图片拷贝失败  -- result:{$resultOfCurl['htmlContent']}";
        writeLog($msg, 0, $logPath);
        return false;
    }
}
?>
